package com.tang.studentinformationmanagementsystem.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.tang.studentinformationmanagementsystem.mapper.ClaMapper;
import com.tang.studentinformationmanagementsystem.pojo.ClaQueryParam;
import com.tang.studentinformationmanagementsystem.pojo.Clazz;

import com.tang.studentinformationmanagementsystem.pojo.PageResult;
import com.tang.studentinformationmanagementsystem.service.ClaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ClasServiceImpl implements ClaService {

    @Autowired
    private ClaMapper claMapper;

    @Override
    public PageResult page(ClaQueryParam claQueryParam) {
        //1.设置分页参数
        PageHelper.startPage(claQueryParam.getPage(), claQueryParam.getPageSize());

        //2.执行查询
        List<Clazz> list = claMapper.page(claQueryParam);
        list.stream().forEach(item -> {
            LocalDate now = LocalDate.now();
            if (now.compareTo(item.getEndDate()) > 0) {
                item.setStatus("已结课");
            } else if (now.compareTo(item.getBeginDate()) < 0) {
                item.setStatus("未开班");
            } else {
                item.setStatus("在读中");
            }
        });
        Page<Clazz> p = (Page<Clazz>) list;

        return new PageResult(p.getTotal(), p.getResult());
    }

    //添加班级
    @Override
    @Transactional
    public void save(Clazz clazz) {
        if (clazz.getId() == null) {
            if (clazz.getCreateTime() == null) {
                clazz.setCreateTime(LocalDateTime.now());
            }
            clazz.setUpdateTime(LocalDateTime.now());
            log.info("添加班级信息：{}", clazz);
            // 执行插入操作
            claMapper.add(clazz);
        } else {

            clazz.setUpdateTime(LocalDateTime.now());
            claMapper.update(clazz);

        }


    }

    //删除班级
    @Override
    public void deleteById(Integer id) {
        claMapper.deleteById(id);
    }

    //根据Id查询班级信息
    @Override
    public Clazz getById(Integer id) {
        Clazz clazz = claMapper.findById(id);
        return clazz;
    }

    @Override
    public List<Clazz> findAll() {
        List<Clazz> all = claMapper.findAll();
        return all;
    }

}
